;var sd = new Date();


(function (o, config) {

    $("#bar").html("Loading tags");
    $("#bar-color").css("width", 10);//reset load bar to begining size
    o.write('<div id="message"></div>' +
        '<div class="progress-bar"><div id="bar"></div></div><br>');
    o.write('<div id="tag_cloud"><div id="loading_tag_cloud"></div><ul id="tag_list"></ul></div>');
    o.write('<section id="postinfo"></section>');


var tag_count=0;


  // create a style switch button
	var switcher = $('<a href="javascript:void(0)" class="btn">Change appearance</a>').toggle(
		function(){
			$("#tag_cloud ul").hide().addClass("alt").fadeIn("fast");
		},
		function(){
			$("#tag_cloud ul").hide().removeClass("alt").fadeIn("fast");
		}
	);
 	$('#sortlinks').append(switcher);

	// create a sort by alphabet button
	var sortabc = $('<a href="javascript:void(0)" class="btn">Sort alphabetically</a>').toggle(
		function(){
			$("#tag_list ul li").tsort({order:"asc"});
		},
		function(){
			$("#tag_list ul li").tsort({order:"desc"});
		}
		);
 	$('#sortlinks').append(sortabc);

	// create a sort by alphabet button
	var sortstrength = $('<a href="javascript:void(0)" class="btn">Sort by useage</a>').toggle(
		function(){
			$("#tag_cloud ul li").tsort({order:"desc",attr:"title"});
		},
		function(){
			$("#tag_cloud ul li").tsort({order:"asc",attr:"title"});
		}
		);
 	$('#sortlinks').append(sortstrength);




    
    function loadmore(filename, filetype) {
        debug(1, "loading external " + filetype + " file."
        );
        if (filetype == "js") { //if filename is a external JavaScript file
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", filename)
        }
        else if (filetype == "css") { //if filename is an external CSS file
            var fileref = document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref)
    }

    function debug(lvl, text, that)/*ts*/ {
        if (!debugging) {
            return;
        }




        $("#message").html("" + text + "");
        var msg = "MSG:" + text + "\n";

        if (typeof(window.console.firebug != "undefined")) {
            switch (lvl) {
                case 0:
                    console.log(msg);
                    break;
                case 1:
                    console.warn(msg);
                    break;
                case 2:
                    console.debug(msg);
                    break;
                case 3:
                    console.error(msg);
                    break;
                default:
                    console.log(msg);
            }
        }
        else if (typeof(window.console != "undefined")) {
            console.log(msg);
        }
        lastcaller = that;
    }

    function f(i) {
        return typeof (i) !== "undefined";
    }

    function p(q, i) {
        return (q - i);
    }

    function m(i, q) {
        return i.sort(function (s, r) {
            return q[s] - q[r];
        });
    }

    function c(r) {
        var i = [];
        var q;
        for (q in r) {
            if (r.hasOwnProperty(q)) {
                i.push(q);
            }
        }
        return i;
    }

    var debugging = true;
    var config = {};
    var g = o.getElementsByTagName("script");
    var a = g[g.length - 1];
    var e = a.src.replace(/^[^\?]+\??/, "").split("&");
    var l = 0;
    var postcount = 0;
    var tag_count = 0;
    var cssurl = "";
    var taglist = new Array;
    var tagblob = new Object;
    var totalposts;

    for (l = 0; l < e.length; l++) {
        var k = e[l].split("=");
        config[k[0]] = unescape(k[1]);
    }
    if (!f(config.minsize)) {
        config.minsize = 120;
    }
    if (!f(config.maxsize)) {
        config.maxsize = 280;
    }
    if (!f(config.math)) {
        config.math = "log";
    }
    if (!f(config.type)) {
        config.type = "photo";
    }
    if (!f(config.apikey)) {
        config.apikey = 'PyezS3Q4Smivb24d9SzZGYSuhMNPQUhMsVetMC9ksuGPkK1BTt';
    }
    if (!f(config.apilimit)) {
        config.apilimit = 20;
    }

    var h = (!f(config.url)) ? o.domain : config.url;
    var j = "http://" + h + "/";


    if (typeof(config.classname) == 'undefined') {
        config.classname = "tag_item";
    }
    if (typeof(config.size)=="undefined"){config.size="100";}

    switch (config.css) {
        case ('default'):
            cssurl = 'default.css';
            break;
        case ('flickr'):
            cssurl = 'default.css';
            break;
        case ('tumblr'):
            cssurl = '"tumlr.css';
            break;
        case ('custom'):

            cssurl = "";
            break;
    }
    var n = "" + cssurl + "";

    loadmore(cssurl, "css");
    ;


    $(o).ready(function () {
        var u = 0;
        var q = [];
        var posttags = [];
        var i = [];
        var r = {};
        var tagcount = 0;
        var z = 0;
        var A = new Array;



function GetPostinfo(post)
{
                        /*Set Post Text*/
                        var text = '';
                        switch (post.type)
                        {
                            case 'text': text += post['title'];break;
                            case 'link': text += post['title']; break;
                            case 'chat': text += post['body']; break;
                            case 'quote': text += post['text']; break;
                            case 'photo': text += post['caption']; break;
                            case 'video': text += post['caption']; break;
                            case 'audio': text += post['caption']; break;
                            case 'answer': text += post['question']; break;
                         }
                            /*Strip HTML from text*/
                        var StrippedText = text.replace(/(<([^>]+)>)/ig,"");
                            /*slice text to the desired length*/
                        if(StrippedText.length>config.len){ StrippedText=StrippedText.slice(0,config.len); StrippedText+='...';}
                            text=StrippedText;

                            if(post.type=='text'){
                        	var fullbody = post.body;
                        	var fullbodyset = $(fullbody);
                         	image += fullbodyset.find('img').attr('src');
                         	}
                            else if(post.type=='audio'){
                        	image+=this.album_art;
                        	}
                            else if(post.type=='photo') {
                                $(post.photos[0]).each(function(i, photo) {
                                    debug(2, "Photos: " + post.photos.length);
                                    $(photo.alt_sizes).each(function(i, alt_size) {
                                        if (config.size == '75') {
                                            if (alt_size.width == '75') {
                                                image = alt_size['url'];
                                            }
                                        }
                                        if (config.size == '100') {
                                            if (alt_size.width == '100') {
                                                image = alt_size['url'];
                                            }
                                        }
                                        if (config.size == '250') {
                                            if (alt_size.width == '250') {
                                                image = alt_size['url'];
                                            }
                                        }
                                    });
                                });

                                /*Post link*/
                                var link = (post['post_url']);
                                /*Set Notes*/


                                var note = 0;
                                var notetext = "";
                                note+=post['note_count'];
                                if (note == 'undefined') {note = '0';}

                                if (note > 0)
                                {
                                notetext = "&hearts;" + (note === 1 ? note + " note ": note + " notes");
                                } else
                                {
                                 notetext = 'Zero notes &hearts;';
                                }
                                debug(1, "Post" + post.id + " type:" + post.type + "\nContent: " + text + "\n Post url:" + link + " notes: "+notetext);


                            }
                        /*Process posts tags*/
                        debug(2, "Post:" + post.id + " has " + post.tags.length + " tags, "+post.tags);
                        $(post.tags).each(function (A, tag) {
                        tagcount++;
                            if (typeof (tag) === "string") {
                                posttags.push(z);
                            }
                        });

                        /*Print floating thumbnail for current post*/
                        var content='<a class="postlink" href="'+link+'" title="'+text+'"><img src="'+image+'" alt=""><div class="notes"></div><p>'+text+' <span id="#notes" class="notes" style="display:inline">&hearts;'+note+'</span></p></a>';
                            var output='<div class="postbox">'+content+'</div>';
                            $('#postinfo').append(output);
                }


        function GetPostbyid(post_id)
        {

            console.groupCollapsed("Starting Getpostbyid: "+post_id);
             var v = j + "api/read/json?callback=?&num=20&start=" + u + "&type=" + config.type;

             v = "http://api.tumblr.com/v2/blog/" + config.url + "/posts?api_key=" + config.apikey + "&id=" + post_id + "&jsonp=?";
             $.getJSON(v, function (w) {
                 $(w.response.posts).each(function (y, post) {
                     GetPostinfo(post);
                 });
             })
        }

        function GetPostbytags(tag)
        {
            var item ="";

             var v = j + "api/read/json?callback=?&num=20&start=" + u + "&type=" + config.type;

             v = "http://api.tumblr.com/v2/blog/" + config.url + "/posts?api_key=" + config.apikey + "&tag=" + tag + "&jsonp=?";
             $.getJSON(v, function (w) {
                     $(w.response.posts).each(function (y, post) {
                      GetPostinfo(post);
                 });

             })
        }



        function GetPosts()
        {

            $("#message").html("Loading Whole Tag List for : "+config.url);
            /*debug(1,"S starting");*/
            var v = j + "api/read/json?callback=?&num=20&start=" + u + "&type=" + config.type;

            v = "http://api.tumblr.com/v2/blog/" + config.url + "/posts?api_key=" + config.apikey + "&limit=" + config.apilimit + "&offset=" + u + "&jsonp=?";

            $.getJSON(v, function (w) {
                $(w.response.posts).each(function (y, x) {
                    $(x.tags).each(function (A, z) {
                        tagcount++;
                        if (typeof (z) === "string") {
                            q.push(z);
                        }
                    });
                });
                totalposts = w.response.blog['posts'];
                var recieved = w.response.posts.length;
                $("#message").html("Loaded:" + u + " posts.");

                if (u + recieved < totalposts) {
                    var x = parseInt(w.response.blog['posts']);
                    var y = parseInt(u);
                    var percentofis = CalculatePercent(u, x);
                    var barwidth = percentofis * 5;
                    $("#bar").html("" + percentofis + "%");
                    $(this).attr("title","Loaded"+percentofis+"%");
                    $("#bar").css("width", barwidth);
                    u = u + config.apilimit;
                    GetPosts();
                } else {
                    ProcessTags();
                }
            });
        }

        function CalculatePercent(value, total) {
            return Math.round(100 * ( value / total ));
        }


        function RedrawTags() {

            ProcessTags();

        }

        function ProcessTags() {
            debug(1, "Processing tags for:" + u + " posts out of" + totalposts + " posts for " + config.url);
            var A = {};
            var B = {};
            var x;
            var tag_count = 0;
            $(q).each(function (D, C) {
                r[C] = (r[C] ? r[C] + 1 : 1);
            });
            var w;

            for (w in r) {
                if (r.hasOwnProperty(w)) {
                    A[w] = r[w];
                    debug (2,"tags: "+A[w]+" "+w);
                }
            }

            if (config.math === "log") {
                for (w in r) {
                    if (r.hasOwnProperty(w)) {
                        r[w] = Math.log(r[w]);
                    }
                }
            }

            var v = c(r);
            var y;
            if (config.order === "frequency") {
                x = m(v, r).reverse();
                for (y in x) {
                    if (x.hasOwnProperty(y)) {
                        B[x[y]] = r[x[y]];
                    }
                }
                r = B;
            } else {
                if (config.order === "alphabetical") {
                    x = v.sort(function (D, F) {
                        var E = String(D).toUpperCase();
                        var C = String(F).toUpperCase();
                        if (E > C) {
                            return 1;
                        }
                        if (E < C) {
                            return -1;
                        }
                        return 0;
                    });
                    for (y in x) {
                        if (x.hasOwnProperty(y)) {
                            B[x[y]] = r[x[y]];
                        }
                    }
                    r = B;
                }
            }
            sizeRange = config.maxsize - config.minsize;
            var z;
            for (z in r) {
                if (r.hasOwnProperty(z)) {
                    i.push(r[z]);
                }
            }
            i.sort(p);
            minCount = i[0];
            maxCount = i[i.length - 1];
            slope = sizeRange / (maxCount - minCount);
            count = 0;
            var hiddentags = 0;
            for (w in r) {
                if (r.hasOwnProperty(w)) {
                    count++;
                    window.status = ("W " + w + "cnt" + count);

                    if (f(config.limit) && config.limit !== "none" && count > config.limit) {
                        break;
                    }
                    if (config.hidelt && A[w] > config.hidelt) {
                        fontSize = Math.round(slope * r[w] - (slope * minCount - config.minsize));
                        title = (A[w] === 1 ? A[w] + " post" : A[w] + " posts");
                        postcount += A[w];
                        tag_count++;
                        GetPostbytags(w);
                        var output = "";
                        switch (config.css) {
                            case ('default'):
                                link = '<a   style="font-size:' + fontSize + '%" href="' + j + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li>' + link + '</li>';

                                break;
                            case ('flickr'):
                                link = '<a   style="font-size:' + fontSize + '%" href="' + j + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li>' + link + '</li>';
                                break;
                            case ('related'):
                                link = '<a   style="font-size:' + fontSize + '%" href="' + j + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li>' + link + '</li>';
                                break;
                            case ('tumblr'):
                                link = '<a  style="font-size:' + fontSize + '%" href="' + j + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li >' + link + '</li>';
                                break;
                            case ('custom'):

                                link = '<a   style="font-size:' + fontSize + '%" href="' + j + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                if (config.classname) {
                                    output = '<li <li  class="' + config.classname + '">' + link + '</li>';
                                }

                            default:
                                link = '<a style="font-size:' + fontSize + '%" href="' + j + "tagged/" + w + '" title="' + title + '">' + w + "</a>";
                                output = '<li style="display:inline;">' + link + '</li>';

                                $("message").html(tag_count+"Tags Processed");

                        }

                        $("#tag_list").append(output);//Create list of tags in the element #tag_list

                        hiddentags++;
                        $("#bar").html(hiddentags + ":hidden tags.");

                    }


                }
            }
            $("#loading_tag_cloud").html("");var nd = new Date();var elapsed = Math.round((nd-sd) / 1000);debug(1,"Ended:"+elapsed)
        }
        $(this).attr("title", this.title+=": Starting "+sd);
        debug(1,"Started:"+sd);
        if (typeof(config.tagged) != "undefined") {
            debug(2, "reading Tags: " + config.tagged);
            var tags = config.tagged.split(',');
            for (var i = 0; i < tags.length; i++) {
                GetPostbytags(tags[i]);
            }
        }
        else if (typeof(config.postid) == "undefined") {
            GetPosts();
        } else {
            debug(2, "reading postids: " + config.postid);
            var postids = config.postid.split(',');
            for (var i = 0; i < postids.length; i++) {
                GetPostbyid(postids[i]);
            }
        }



    });}(document));